package com.example.pcbcsmbackend.controller;

import com.example.pcbcsmbackend.entity.Order;
import com.example.pcbcsmbackend.entity.OrderDetail;
import com.example.pcbcsmbackend.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/order")
@CrossOrigin(origins = "http://localhost:8080")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    // 创建订单
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createOrder(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            Integer userId = Integer.parseInt(request.get("userId").toString());
            BigDecimal totalAmount = new BigDecimal(request.get("totalAmount").toString());
            String shippingAddress = (String) request.get("shippingAddress");
            String contactInfo = (String) request.get("contactInfo");
            String paymentMethod = (String) request.get("paymentMethod");
            
            // 解析订单详情
            List<Map<String, Object>> detailsData = (List<Map<String, Object>>) request.get("orderDetails");
            List<OrderDetail> orderDetails = new ArrayList<>();
            
            // 订单对象先创建，但不安插到数据库
            Order tempOrder = new Order();

            for (Map<String, Object> detailData : detailsData) {
                Integer productId = Integer.parseInt(detailData.get("productId").toString());
                Integer quantity = Integer.parseInt(detailData.get("quantity").toString());
                BigDecimal unitPrice = new BigDecimal(detailData.get("unitPrice").toString());
                
                OrderDetail orderDetail = new OrderDetail(tempOrder, productId, quantity, unitPrice);
                orderDetails.add(orderDetail);
            }
            
            Order order = orderService.createOrder(userId, totalAmount, shippingAddress, 
                                                  contactInfo, paymentMethod, orderDetails);
            response.put("success", true);
            response.put("message", "订单创建成功");
            response.put("order", order);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 根据用户ID获取订单
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getOrdersByUserId(@PathVariable Integer userId) {
        Map<String, Object> response = new HashMap<>();
        List<Order> orders = orderService.getOrdersByUserId(userId);
        response.put("success", true);
        response.put("orders", orders);
        return ResponseEntity.ok(response);
    }
    
    // 根据订单ID获取订单详情
    @GetMapping("/{orderId}")
    public ResponseEntity<Map<String, Object>> getOrderById(@PathVariable Integer orderId) {
        Map<String, Object> response = new HashMap<>();
        Optional<Order> order = orderService.findById(orderId);
        if (order.isPresent()) {
            List<OrderDetail> orderDetails = orderService.getOrderDetails(orderId);
            response.put("success", true);
            response.put("order", order.get());
            response.put("orderDetails", orderDetails);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "订单不存在");
            return ResponseEntity.notFound().build();
        }
    }
    
    // 获取所有订单（管理员功能）
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> getAllOrders() {
        Map<String, Object> response = new HashMap<>();
        List<Order> orders = orderService.getAllOrders();
        response.put("success", true);
        response.put("orders", orders);
        return ResponseEntity.ok(response);
    }
    
    // 根据状态获取订单（管理员功能）
    @GetMapping("/status/{status}")
    public ResponseEntity<Map<String, Object>> getOrdersByStatus(@PathVariable String status) {
        Map<String, Object> response = new HashMap<>();
        List<Order> orders = orderService.getOrdersByStatus(status);
        response.put("success", true);
        response.put("orders", orders);
        return ResponseEntity.ok(response);
    }
    
    // 更新订单状态
    @PutMapping("/status")
    public ResponseEntity<Map<String, Object>> updateOrderStatus(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            Integer orderId = Integer.parseInt(request.get("orderId").toString());
            String status = (String) request.get("status");
            
            orderService.updateOrderStatus(orderId, status);
            response.put("success", true);
            response.put("message", "订单状态更新成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 更新订单信息（管理员功能）
    @PutMapping("/update/{orderId}")
    public ResponseEntity<Map<String, Object>> updateOrder(@PathVariable Integer orderId, @RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String orderStatus = (String) request.get("orderStatus");
            String paymentMethod = (String) request.get("paymentMethod");
            String shippingAddress = (String) request.get("shippingAddress");
            String contactInfo = (String) request.get("contactInfo");
            BigDecimal totalAmount = new BigDecimal(request.get("totalAmount").toString());
            
            // 解析订单详情
            List<Map<String, Object>> detailsData = (List<Map<String, Object>>) request.get("orderDetails");
            List<OrderDetail> orderDetails = new ArrayList<>();
            
            for (Map<String, Object> detailData : detailsData) {
                Integer detailId = detailData.get("detailId") != null ? 
                    Integer.parseInt(detailData.get("detailId").toString()) : null;
                Integer productId = Integer.parseInt(detailData.get("productId").toString());
                Integer quantity = Integer.parseInt(detailData.get("quantity").toString());
                BigDecimal unitPrice = new BigDecimal(detailData.get("unitPrice").toString());
                
                OrderDetail orderDetail = new OrderDetail();
                if (detailId != null) {
                    orderDetail.setDetailId(detailId);
                }
                orderDetail.setProductId(productId);
                orderDetail.setQuantity(quantity);
                orderDetail.setUnitPrice(unitPrice);
                orderDetails.add(orderDetail);
            }
            
            Order updatedOrder = orderService.updateOrder(orderId, orderStatus, paymentMethod, 
                                                        shippingAddress, contactInfo, totalAmount, orderDetails);
            response.put("success", true);
            response.put("message", "订单信息更新成功");
            response.put("order", updatedOrder);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 获取订单详情（商品列表）
    @GetMapping("/details/{orderId}")
    public ResponseEntity<Map<String, Object>> getOrderDetails(@PathVariable Integer orderId) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<OrderDetail> orderDetails = orderService.getOrderDetails(orderId);
            response.put("success", true);
            response.put("orderDetails", orderDetails);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 批量更新订单状态（管理员功能）
    @PutMapping("/batch/status")
    public ResponseEntity<Map<String, Object>> batchUpdateOrderStatus(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<Integer> orderIds = (List<Integer>) request.get("orderIds");
            String status = (String) request.get("status");
            
            orderService.batchUpdateOrderStatus(orderIds, status);
            response.put("success", true);
            response.put("message", "批量更新订单状态成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "批量更新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 删除订单（管理员功能）
    @DeleteMapping("/{orderId}")
    public ResponseEntity<Map<String, Object>> deleteOrder(@PathVariable Integer orderId) {
        Map<String, Object> response = new HashMap<>();
        try {
            orderService.deleteOrder(orderId);
            response.put("success", true);
            response.put("message", "订单删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 批量删除订单（管理员功能）
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> batchDeleteOrders(@RequestBody List<Integer> orderIds) {
        Map<String, Object> response = new HashMap<>();
        try {
            orderService.batchDeleteOrders(orderIds);
            response.put("success", true);
            response.put("message", "批量删除订单成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "批量删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
} 